<script lang="ts">
import { NTreeSelect, type TreeSelectOption } from 'naive-ui'
import { defineComponent, shallowRef, h, onMounted } from 'vue'
import { sendRequest } from '@/utils/api'
import type { HttpResponse } from '@/utils/http'
import type { DicTreeModel } from '@/api/dic'

function isDefined<T = unknown>(value: T): value is NonNullable<T> {
  return value !== undefined && value !== null
}

interface Tree {
  childList?: Tree[]
}

function deepRemove(value: Tree) {
  if (value.childList && value.childList.length === 0) {
    delete value.childList
    return
  }
  value.childList?.forEach((e) => deepRemove(e))
}

export default defineComponent({
  name: 'VersionTypeCascadeSelect',
  props: {} as any,
  emits: ['update:value', 'updateValue'],
  setup(props, { emit }) {
    const options = shallowRef<TreeSelectOption[]>([])
    const loading = shallowRef(false)

    const queryOptions = async () => {
      loading.value = true

      try {
        const [error, res] = await sendRequest<HttpResponse<DicTreeModel[]>>({
          module: 'collectProcess',
          api: 'listTreeAll',
          override: {
            params: {
              statusCode: 'A4901'
            }
          }
        })
        if (error) throw error
        if (res.code !== 0) throw new Error(res.msg)
        res.data.forEach((e) => deepRemove(e as unknown as Tree))
        options.value = res.data
      } catch (error) {
        console.error(error)
      } finally {
        loading.value = false
      }
    }

    onMounted(queryOptions)

    return () =>
      h(NTreeSelect, {
        value: props.value,
        onUpdateValue: (v) => {
          emit('updateValue', v)
          emit('update:value', v)
        },
        options: options.value,
        loading: loading.value,
        disabled: props.disabled,
        clearable: props.clearable,
        labelField: props.labelField || 'classificationName',
        keyField: props.keyField || 'classificationCode',
        childrenField: props.childrenField || 'childList',
        placeholder: props.placeholder || '请选择版本类型',
        multiple: props.multiple,
        showPath: props.showPath||true,
        separator: props.separator || '->',
        filterable: isDefined(props.filterable) ? props.filterable : true
      })
  }
})
</script>
